//
//  AppDelegate.swift
//  LeGou
//
//  Created by lxm on 2022/7/15.
//

import UIKit
import AppTrackingTransparency
import AdSupport

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    
    var window: UIWindow?
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        URLNavigationMap.initialize(navigator: router)
        IQKeyboardManager.shared().disabledDistanceHandlingClasses.add(LoginCodeVerifyVC.classForCoder())
        IQKeyboardManager.shared().disabledDistanceHandlingClasses.add(PsdTradeCodeVerify.classForCoder())
        IQKeyboardManager.shared().disabledDistanceHandlingClasses.add(PhoneBindVC.classForCoder())
        IQKeyboardManager.shared().disabledDistanceHandlingClasses.add(PhoneInputVC.classForCoder())
        IQKeyboardManager.shared().disabledDistanceHandlingClasses.add(InviteCodeInputVC.classForCoder())
        IQKeyboardManager.shared().disabledDistanceHandlingClasses.add(TradePwdSet.classForCoder())
        
        ZMAppShareData.share.requestUserInfo { ok in
            
        }
        
                
//        ZMAppShareData.share.clearUserInfo()
        registerOperation(launchOptions: launchOptions)
        self.window = UIWindow.init(frame: SCREEN_BOUNDS)
        self.window?.backgroundColor = UIColor.white
        self.window?.rootViewController = ZMAppShareData.share.provideStartVC()
        self.window?.makeKeyAndVisible()
        
        
        
//        if developMode != 1 {
//           // 非发布环境使用测试工具
//           _ = rx.observe(UIViewController.self, "window.rootViewController").subscribe { (_) in
//               self.window?.addSubview((TestNetTool.shareInstance()?.testBtn!)!)
//           }
//       }
        
//        let famliys = UIFont.familyNames
//        for s in famliys {
//            print("字体族名称:\(s)")
//            let fonts = UIFont.fontNames(forFamilyName: s)
//            for f in fonts {
//                print("字体名称\(f)")
//            }
//        }

        AlibcTradeUltimateSDK.sharedInstance().asyncInit {
            ZMLog(message: "百川初始化成功")
            AlibcTradeUltimateSDK.sharedInstance().enableLocalDebug(true)
        } failure: { err in
            ZMLog(message: err)
            ZMLog(message: "百川初始化失败")
        }
        
        addNotifacation()

        return true
    }
    
    func addNotifacation() {
        NotificationTool.shard.requestAuthorization { ok, e in
            
        }
        
        NotificationTool.shard.getNotification()
//        UNUserNotificationCenter.current().get
    }
    
    func registerOperation(launchOptions: [UIApplication.LaunchOptionsKey: Any]?) {
        ZMShareManager.shareSDKRegister()
        
        CommonService.shared.appInit()
        
        if #available(iOS 15.0, *) {
            UITableView.appearance().sectionHeaderTopPadding = 0
        } else {
            // Fallback on earlier versions
        }
    }
    
    func applicationDidBecomeActive(_ application: UIApplication) {
        // 为了过审核，需要请求下权限
        if #available(iOS 14, *) {
            ATTrackingManager.requestTrackingAuthorization { s in
                if s == .authorized {
                    let _ = ASIdentifierManager.shared().advertisingIdentifier
                }
                else {
                }
            }
        } else {
            if ASIdentifierManager.shared().isAdvertisingTrackingEnabled {
                let _ = ASIdentifierManager.shared().advertisingIdentifier
            }
            else {
            }
        }
    }
        
    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        AlibcTradeUltimateSDK.sharedInstance().application(app, open: url)
        AlipaySDK().processAuth_V2Result(url) { (response) in
            guard let res = response else  {return}
            ZMNotification.shard.subject.onNext(.aliAuthSuccess(res as! [String : Any]))
        }
        
        /// 支付宝支付回调
        AlipaySDK.defaultService()?.processOrder(withPaymentResult: url, standbyCallback: { (resultDic) in
            guard let resultDic = resultDic else {return}
            let orderState = JSON(resultDic)["resultStatus"].intValue
            switch orderState {
                case 9000:
                    ZMNotification.shard.subject.onNext(.payOtion(.success))
                    break
                case 8000:
                    ZMNotification.shard.subject.onNext(.payOtion(.handling))
                    break
                case 4000:
                    ZMNotification.shard.subject.onNext(.payOtion(.payFaild))
                    break
                case 6001:
                    ZMNotification.shard.subject.onNext(.payOtion(.payCancel))
                    break
                case 6002:
                    ZMNotification.shard.subject.onNext(.payOtion(.netBad))
                    break
                default:break
            }
        })
        
        if url.host == "pay" {
            WXApi.handleOpen(url, delegate: self)
        }
//        else if url.absoluteString.contains(WeChatAppID),let code = getQueryDic(query: url.query ?? "")["code"] {
//            disposeBag = DisposeBag()
//            ZMLoginAPI.wechat_access_token(code: code).rxRequest(type: [String : Any].self).subscribe(onNext:{ [unowned self] resp in
//            print(JSON(resp))
//            }).disposed(by: disposeBag)
//        }
        return true
    }

}

extension AppDelegate : WXApiDelegate {
    func onResp(_ resp: BaseResp) {
        guard let r = resp as? PayResp else {return}
        switch r.errCode {
        case 0:
            ZMNotification.shard.subject.onNext(.payOtion(.success))
            break
        default:
            ZMNotification.shard.subject.onNext(.payOtion(.payFaild))
        }
    }
}
